package com.ls.business.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.business.entity.Expense;
import com.ls.business.mapper.ExpenseMapper;
import com.ls.business.service.IExpenseService;
import com.ls.common.Constast;
import com.ls.common.DataGridView;
import com.ls.common.PageModel;
import com.ls.common.ResultObj;
import com.ls.common.utils.WebUtils;
import com.ls.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author lisheng
 * @Date 2025/05/07 21:05
 **/
@RestController
@RequestMapping("/expense")
public class ExpenseController {

    @Autowired
    private IExpenseService expenseService;

    @Autowired
    private ExpenseMapper expenseMapper;

    @GetMapping("/list")
    public DataGridView list(PageModel pageModel) {
        SysUser u = (SysUser) WebUtils.getSession().getAttribute("user");
        if (u == null) {
            return new DataGridView(0L, null);
        }

        QueryWrapper<Expense> queryWrapper = new QueryWrapper<>();
        if (!"system".equals(u.getLoginname())) {
            queryWrapper.eq("applicant", u.getLoginname());
        }

        Page<Expense> page = new Page<>(pageModel.getPage(), pageModel.getLimit());
        Page<Expense> expensePage = expenseService.page(page, queryWrapper);
        return new DataGridView(expensePage.getTotal(), expensePage.getRecords());
    }

    @PostMapping("/save")
    public ResultObj save(@RequestBody Expense expense) {
        try {
            SysUser u = (SysUser) WebUtils.getSession().getAttribute("user");
            if (ObjectUtil.isEmpty(u)) {
                return new ResultObj(Constast.ERROR, "操作失败：用户未登录！");
            }
            if (ObjectUtil.isEmpty(expense.getId())) {
                expense.setDeclarantId(u.getId());
                expense.setDeclarant(u.getName());
                expense.setCode("BX" + System.currentTimeMillis());
            }
            boolean success = expenseService.saveOrUpdate(expense);
            return success ? new ResultObj(Constast.OK, "操作成功") : new ResultObj(Constast.ERROR, "操作失败");
        } catch (Exception e) {
            return new ResultObj(Constast.ERROR, "操作失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}/delete")
    public ResultObj delete(@PathVariable Integer id) {
        boolean success = expenseService.removeById(id);
        return success ? ResultObj.DELETE_SUCCESS : ResultObj.DELETE_ERROR;
    }
}
